package _binary_tree

import common.TreeNode
import org.junit.Assert
import org.junit.Test
import java.util.*
import kotlin.collections.ArrayList

/*
  https://programmercarl.com/0102.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%B1%82%E5%BA%8F%E9%81%8D%E5%8E%86.html
  https://leetcode.cn/problems/binary-tree-level-order-traversal/description/

  102. 二叉树的层序遍历
  给你二叉树的根节点 root ，返回其节点值的 层序遍历 。 （即逐层地，从左到右访问所有节点）。

示例 1：
输入：root = [3,9,20,null,null,15,7]
输出：[[3],[9,20],[15,7]]

示例 2：
输入：root = [1]
输出：[[1]]

示例 3：
输入：root = []
输出：[]
 */
class leetcode_102 {

    @Test
    fun test_1() {
        val n3 = TreeNode(3)
        val n9 = TreeNode(9)
        val n20 = TreeNode(20)
        val n15 = TreeNode(15)
        val n7 = TreeNode(7)
        n3.left = n9
        n3.right = n20
        n20.left = n15
        n20.right = n7

        val actual = levelOrder(n3)
        val expected = arrayListOf(arrayListOf(3), arrayListOf(9, 20), arrayListOf(15, 7))
        Assert.assertEquals(expected.toString(), actual.toString())
    }

    @Test
    fun test_2() {
        val n1 = TreeNode(1)
        val actual = levelOrder(n1)
        val expected = arrayListOf(arrayListOf(1))
        Assert.assertEquals(expected.toString(), actual.toString())
    }

    @Test
    fun test_3() {
        val actual = levelOrder(null)
        val expected = ArrayList<ArrayList<Int>>()
        Assert.assertEquals(expected.toString(), actual.toString())
    }

    private fun levelOrder(root: TreeNode?): List<List<Int>> {
        // S - N
        // T - N
        val result: ArrayList<ArrayList<Int>> = ArrayList<ArrayList<Int>>()
        if (null == root) {
            return result
        }

        var size: Int
        val queue: LinkedList<TreeNode> = LinkedList<TreeNode>()
        queue.offer(root)
        while (!queue.isEmpty()) {
            size = queue.size
            val list: ArrayList<Int> = ArrayList<Int>()
            while (size-- > 0) {
                val node: TreeNode = queue.poll()
                list.add(node.`val`)
                node.left?.let {
                    queue.offer(it)
                }
                node.right?.let {
                    queue.offer(it)
                }
            }
            result.add(list)
        }
        return result
    }
}